package cn.edu.scujcc;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class AddressBookService {
	@Autowired
	private AddressBookRepository repo;
	public AddressBook createAddressBook(AddressBook ab) {
		
		AddressBook result = null;
		result = repo.save(ab);
		return result;
	}
    public AddressBook updateAddressBook(AddressBook ab) {
		
    	AddressBook result = null;
    	result = getAddressBook(ab.getId());
		if (result != null) {
			if (ab.getName() != null) {
				result.setName(ab.getName());
			}
			if (ab.getTelnum() != null) {
				result.setTelnum(ab.getTelnum());
			}
			if (ab.getHeadportrait() != null) {
				result.setHeadportrait(ab.getHeadportrait());
			}
			result = repo.save(result);
		}
		
		return result;
	}
	public List<AddressBook> getAllAddressBook() {
		
		List<AddressBook> result = null;
		result = repo.findAll();
		return result;
	}
	public AddressBook getAddressBook(String name) {
		
		AddressBook result = null;
		Optional<AddressBook> op = repo.findById(name);
		if (op.isPresent()) {
			result = op.get();
		}
		return result;
	}
	

	public boolean deleteAddressBook(String name) {
		
		boolean result = true;
		try {
			repo.deleteById(name);
		} catch (Exception c) {
			result = false;
		}
		return result;
	}
	

	public List<AddressBook> searchAddressBook(String telnum) {
		
		List<AddressBook> result = null;
		result = repo.findByTelnum(telnum);
		return result;
	}
}
